﻿#region File and License Information
/*
<File>
	<Copyright>Copyright © 2007, Daniel Vaughan. All rights reserved.</Copyright>
	<License see="prj:///Documentation/License.txt"/>
	<Owner Name="Daniel Vaughan" Email="dbvaughan@gmail.com"/>
	<CreationDate>2008-05-04 19:49:23Z</CreationDate>
	<LastSubmissionDate>$Date: $</LastSubmissionDate>
	<Version>$Revision: $</Version>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using DanielVaughan.Logging.ClientLogging;

namespace DanielVaughan.Logging.Silverlight.UI
{
    public partial class LogViewer
    {
		/// <summary>
		/// Gets or sets a value indicating whether to display all
		/// logging messages, whether they are sent to the server or not.
		/// </summary>
		/// <value><c>true</c> if in offline mode; otherwise, <c>false</c>.</value>
		public bool OfflineMode { get; set; }

        public LogViewer()
        {
            InitializeComponent();
			Loaded += LogViewer_Loaded;
        }

		void LogViewer_Loaded(object sender, RoutedEventArgs e)
		{
			//TextBlock_Version.Text = "1.1.4";//Assembly.GetExecutingAssembly().GetName().Version.ToString();
			ListBox_Entries.Items.Clear();
			ListBox_Entries.SelectionChanged += ListBox_Entries_SelectionChanged;

			LogManager.WriteRequested += LogManager_LogEntrySendAttempt;
			LogManager.LogEntrySent += LogManager_LogEntrySent;
			LogManager.Error += LogManager_Error;
		}

		void LogManager_Error(object sender, InternalMessageEventArgs e)
		{
			string errorMessage = e.Exception != null ? 
				e.Exception.Message + "  " + e.Exception.StackTrace 
				: string.Empty;
			Dispatcher.BeginInvoke(() => TextBlock_Messages.Text += e.Message + "   " + errorMessage + "\n");
		}

		void ListBox_Entries_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var entryData = ListBox_Entries.SelectedItem as LogEntryData;
			if (entryData != null)
			{
				TextBlock_Entry.Text = entryData.Message;
			}
		}

		void LogManager_LogEntrySendAttempt(object sender, LogEventArgs e)
		{
			if (OfflineMode && e.LogEntryData != null)
			{
				DisplayLogEntry(e.LogEntryData);
			}
		}

		void LogManager_LogEntrySent(object sender, LogEventArgs e)
		{
			if (!OfflineMode && e.LogEntryData != null)
			{
				DisplayLogEntry(e.LogEntryData);
			}
		}

		void DisplayLogEntry(LogEntryData logEntryData)
		{
			if (Dispatcher.CheckAccess())
			{
				ListBox_Entries.Items.Insert(0, logEntryData);
			}
			else
			{
				Dispatcher.BeginInvoke(() => ListBox_Entries.Items.Insert(0, logEntryData));
			}
		}


    }
}
